
import React from 'react';
import {  Button,message,Upload,Icon } from 'antd';
import {baseUrl} from '../../config';
import * as Utils from '../../utils_yyr/action';
//apiService  调用的接口文件  apiPath接口路径 parameter明确的参数 search为true代表加入查询条件  fileName下载的文件名  buttonName按钮名称
class FileDown extends React.Component {
  state = {
  };
  downFile=()=>{
    const p=this.props;
    if(p.data){
      delete p.data.pageNum;
      delete p.data.pageSize;
    }
    this[p.method?p.method:'get'](p.apiPath,{data:p.data?p.data:{},responseType: 'blob'}).then(res=>{
      //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
      let url = window.URL.createObjectURL(new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
      // 创建A标签
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      // 设置的下载文件文件名
      const fileName = decodeURI(p.fileName);
      // 触发点击方法
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
    })
  }

  render(){
    const p=this;
    return(
      <Button icon="arrow-down" onClick={()=>this.downFile()} type="primary">{p.props.buttonName}</Button>
    )
  }
}
//apiService  调用的接口文件  apiPath接口完整路径  eg:/lj-mes-production/planTemplate/fileUpload load是否刷新父组件数据  parameter参数  buttonName按钮名称
class FileUpload extends React.Component {
  state = {
  };

  render(){
    const p=this;
    const props = {
					name: 'file',
					action:baseUrl+p.props.apiPath,
					headers: {
						Token: localStorage.getItem('token'),
          },
          data:p.props.parameter?p.props.parameter:{},
					multiple:true,
          showUploadList:false,
					onChange(info) {
            console.log(info)
						if (info.file.status !== 'uploading') {
						}
						if (info.file.status === 'done') {
              if(info.file.response.code!==200){
                Utils.openNotification('warning',info.file.response.msg)
                return
              }
							message.success(`${info.file.name} 上传成功.`);
              if(p.props.load){
                p.props.fetch();
              }
              if(p.props.fileId){
                console.log(p.props.fileId)
                p.props.getFileId(info.file.response.data.id);
              }
						} else if (info.file.status === 'error') {
							message.error(`${info.file.name} 上传失败.`);
						}
					},
				};
    return(
        <Upload {...props} style={{display:'inline-block'}}><Button type='primary'><Icon type="upload" />{p.props.buttonName}</Button></Upload>
    )
  }
}


export  {FileDown,FileUpload};
